<template>
    <div class="container">
        <div class="header">

            <div style="margin-left: 80px;" @click="goHome">
                <span class='hometxt'>我的课程</span>
            </div>
            <el-button round v-if="courseInfo.auth == 'teacher_per'" @click="showDia">修改课程信息</el-button>
            <UserAcatar @transfer="change" />
        </div>
        <!-- 修改信息弹框 -->
        <el-dialog title="课程信息" :visible.sync="dialogFormVisible">
            <el-form :model="form">

                <el-form-item style="display: flex;justify-content: center;align-items: center;">

                    <div style="display: flex;justify-content: center;align-items: center;">
                        <el-button @click="show" id="btn" style="display: none;"></el-button>
                        <label for="btn">
                            <div v-show="!fileContent" class="imgbox"
                                style="width: 200px;height: 115px;cursor: pointer;margin-right: 40px;">
                                <i v-if="!courseMsg.course_image" class="el-icon-picture-outline"></i>
                                <el-image v-else class="img" :src="courseMsg.course_image" fit="contain" />
                            </div>
                            <div class="imgbox" v-show="fileContent"
                                style="width: 200px;height: 115px;cursor: pointer;margin-right: 40px;">
                                <el-image :src="fileContent" class="img" fit="contain" />
                            </div>
                        </label>
                        <el-button type="success" plain @click="uploadImg">确认上传</el-button>
                    </div>
                </el-form-item>

                <el-form-item label="学生人数">
                    <el-input v-model="form.num" autocomplete="off"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="Sub">确 定</el-button>
            </div>
        </el-dialog>
        <!-- 图片裁剪弹框 -->
        <Cropper :dialogCropper="dialogCropper" :imgUrl="nowImage" :fixedNumber="[16, 9]" :loading="loading"
            @closeDialog="dialogCropper = false" @blobData="handleBlobData" v-if="nowImage">
        </Cropper>

        <div class="content">
            <!-- 课程详情页 -->
            <div class="courses">

                <div style="display: flex;justify-content: space-between;align-items: center;margin-bottom: 20px;">

                    <!-- 课程简介 -->
                    <div>
                        <span style="border-bottom: 3px solid #cceabb;font-size: 26px;">课程简介</span>
                        <div style="width: 500px;height: 200px;margin-top: 20px;">
                            <div>
                                <span>
                                    报名时间: {{ courseMsg.apply_start_date }} -- {{ courseMsg.apply_end_date }}
                                </span>
                                <el-tag type="info" size="mini" style="margin-left: 20px;"
                                    v-if="new Date(courseMsg.apply_end_date) < new Date()">
                                    报名已结束
                                </el-tag>
                                <el-tag type="success" size="mini" style="margin-left: 20px;"
                                    v-if="new Date(courseMsg.apply_end_date) > new Date() && new Date() > new Date(courseMsg.apply_start_date)">
                                    报名进行中
                                </el-tag>
                            </div>
                            <div>
                                <span>
                                    开课时间: {{ courseMsg.start_date }} -- {{ courseMsg.end_date }}
                                </span>
                                <el-tag type="info" size="mini" style="margin-left: 20px;"
                                    v-if="new Date(courseMsg.end_date) < new Date()">
                                    课程已结束
                                </el-tag>
                                <el-tag type="info" size="mini" style="margin-left: 20px;"
                                    v-if="new Date(courseMsg.apply_end_date) < new Date() && new Date(courseMsg.start_date) > new Date()">
                                    暂时未开课
                                </el-tag>
                                <el-tag type="success" size="mini" style="margin-left: 20px;"
                                    v-if="new Date(courseMsg.end_date) > new Date() && new Date() > new Date(courseMsg.start_date)">
                                    课程进行中
                                </el-tag>
                            </div>
                            <span style="margin-top: 10px;display: block;line-height: 1.5;height: 150px;overflow: auto;">
                                {{ courseMsg.course_desc }}
                            </span>
                        </div>
                    </div>

                    <!-- 课程图片 -->
                    <div style="">
                        <div class="imgbox">
                            <i v-if="!courseMsg.course_image" class="el-icon-picture-outline"></i>
                            <el-image v-else class="img" :src="courseMsg.course_image" fit="cover" />
                        </div>
                        <div style="display: flex;align-items: center;justify-content: space-around;margin-top: 10px;">
                            <span style="font-size: large;">
                                {{ courseMsg.course_name }}
                            </span>
                        </div>
                    </div>

                </div>

                <div style="display: flex;justify-content: space-between;">
                    <div id="main"
                        style="width: 500px;height: 320px;display: flex;justify-content: center;align-items: center;">
                    </div>
                    <!-- 课程成员弹框 -->
                    <el-dialog title="课程成员" :visible.sync="dialogUsers">
                        <div style="overflow:auto;max-height: 400px;">
                            <ul v-infinite-scroll="handleScroll" :infinite-scroll-disabled="listLoading"
                                v-loading="listLoading" element-loading-text="Loading">
                                <li v-for="i in list"
                                    style="display: flex;align-items: center;margin-top: 10px;text-align: center;">
                                    <el-avatar :size="40" shape="square"
                                        :src="i.avatar ? `http://localhost:3000/image/getavatar/${encodeURIComponent(i.avatar)}` : circleUrl"></el-avatar>
                                    <span style="margin-left: 20px;display: inline-block;width: 100px;text-align: center;">
                                        {{ i.student_name }}
                                    </span>
                                    <span style="margin-left: 20px;display: inline-block;width: 100px;text-align: center;">
                                        {{ i.student_id }}
                                    </span>
                                    <span style="margin-left: 20px;display: inline-block;width: 100px;text-align: center;">
                                        {{ i.institute_name }}
                                    </span>
                                    <span style="margin-left: 20px;display: inline-block;width: 100px;text-align: center;">
                                        {{ i.grade_name }}
                                    </span>
                                    <span style="margin-left: 20px;display: inline-block;width: 100px;text-align: center;">
                                        {{ i.class_name }}
                                    </span>
                                </li>
                            </ul>
                        </div>
                        <div slot="footer" class="dialog-footer"
                            v-if="courseInfo.auth == 'teacher_per' && new Date(courseMsg.apply_start_date) < new Date() && new Date() < new Date(courseMsg.start_date)">
                            <el-button type="primary" @click="Invite">添加学生</el-button>
                        </div>
                    </el-dialog>
                    <!-- 添加新成员 -->
                    <el-drawer title="添加课程成员" :visible.sync="drawer" direction="rtl" size="50%">
                        <!-- <el-table v-loading="listLoading" :data="list" element-loading-text="Loading" border fit
                            highlight-current-row height="560" v-infinite-scroll="handleScroll"
                            :infinite-scroll-disabled="listLoading"> -->
                        <el-select v-model="class_id" clearable placeholder="班级" @change="pitch">
                            <el-option v-for="item in classOptions" :key="item.value" :label="item.label"
                                :value="item.value">
                            </el-option>
                        </el-select>
                        <el-table ref="multipleTable" :data="drawList" tooltip-effect="dark" style="width: 100%"
                            @selection-change="handleSelectionChange" v-loading="drawLoading"
                            element-loading-text="Loading..." fit height="520">
                            <el-table-column type="selection" width="45">
                            </el-table-column>
                            <el-table-column align="center" label="头像" width="100">
                                <template slot-scope="scope">
                                    <el-avatar :size="40" shape="square"
                                        :src="scope.row.avatar ? `http://localhost:3000/image/getavatar/${encodeURIComponent(scope.row.avatar)}` : circleUrl"></el-avatar>
                                </template>
                            </el-table-column>
                            <el-table-column align="center" label="姓名" width="120">
                                <template slot-scope="scope">
                                    {{ scope.row.student_name }}
                                </template>
                            </el-table-column>
                            <el-table-column align="center" label="学号" width="120">
                                <template slot-scope="scope">
                                    {{ scope.row.student_id }}
                                </template>
                            </el-table-column>
                            <el-table-column align="center" label="学院" width="120">
                                <template slot-scope="scope">
                                    {{ scope.row.institute_name }}
                                </template>
                            </el-table-column>
                            <el-table-column label="年级" width="110" align="center">
                                <template slot-scope="scope">
                                    <span>{{ scope.row.grade_name }}</span>
                                </template>
                            </el-table-column>
                            <el-table-column label="班级" width="110" align="center">
                                <template slot-scope="scope">
                                    {{ scope.row.class_name }}
                                </template>
                            </el-table-column>
                        </el-table>
                        <div style="margin-top: 20px;">
                            <el-button @click="toggleSelection()">清空选项</el-button>
                            <el-button type="primary" @click="InviteConfirm">确认添加</el-button>
                        </div>
                    </el-drawer>

                    <div style="display: flex;flex-direction: column;height: 320px;">
                        <!-- 任课教师 -->
                        <div>
                            <span style="border-bottom: 3px solid #cceabb;font-size: 26px;">任课教师</span>
                            <div style="width: 500px;height: 100px;margin-top: 20px;overflow: auto;">
                                <div
                                    style="display: flex;align-items: center;box-shadow: 0px 0px 0px 0px rgba(0, 0, 0, 0.1), 1px 1px 4px 0px rgba(0, 0, 0, 0.1), 6px 5px 8px 0px rgba(0, 0, 0, 0.09);background-color: #fff;padding: 5px;">
                                    <!-- 头像 -->
                                    <div class="Tavatar" v-if="!courseMsg.avatar"
                                        style="background-color: #ccc;display: flex;justify-content: center;align-items: center;">
                                        <i class="el-icon-picture-outline"></i>
                                    </div>
                                    <el-image v-else class="Tavatar" :src="courseMsg.avatar" />
                                    <!-- 提示 -->
                                    <el-popover placement="top-start" title="教师经历" width="500" trigger="hover"
                                        :content="courseMsg.teacher_experience ? courseMsg.teacher_experience : '老师有点害羞，还没有公布老师经历呢!'">
                                        <div style="display: flex;flex-direction: column;width: 400px;cursor: pointer;"
                                            slot="reference">
                                            <span style="margin-left: 30px;font-size: 18px;">
                                                {{ courseMsg.teacher_name }}
                                            </span>
                                            <span
                                                style="margin-left: 30px;color: #cceabb;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;">
                                                {{ courseMsg.teacher_experience }}
                                            </span>
                                        </div>
                                    </el-popover>
                                </div>
                            </div>
                        </div>

                        <!-- 参考教材 -->
                        <div>
                            <span style="border-bottom: 3px solid #cceabb;font-size: 26px;">基础信息</span>
                            <div style="margin-top: 20px;display: flex;flex-direction: column;">
                                <div style="margin-bottom: 10px;">学院：{{ courseMsg.institute_name }}</div>
                                <div>学分：{{ courseMsg.course_credit }}</div>
                            </div>
                        </div>
                    </div>
                </div>

            </div>

        </div>
    </div>
</template>
  
<script>
import UserAcatar from "@/components/UserAcatar.vue";
import Cropper from "../Cropper.vue";

export default {
    name: 'MyCourse',
    components: {
        UserAcatar,
        Cropper
    },
    data() {
        return {
            userInfo: {},
            courseInfo: {},
            courseMsg: {
                course_image: ''
            },
            dialogFormVisible: false,
            form: {
                num: 0
            },
            dialogUsers: false,
            listLoading: false,
            fileData: '',
            fileContent: '',
            dialogCropper: false,
            loading: false,
            list: null,
            currentPage: 1,
            total: 1,
            drawer: false,
            class_id: '',
            classOptions: [
                {
                    value: '选项1',
                    label: '黄金糕'
                }, {
                    value: '选项2',
                    label: '双皮奶'
                }
            ],
            drawList: null,
            drawLoading: false,
            multipleSelection: [],
            nowImage: "",
            squareUrl:
                "https://cube.elemecdn.com/9/c2/f0ee8a3c7c9638a54940382568c9dpng.png",
            circleUrl:
                "https://cube.elemecdn.com/3/7c/3ea6beec64369c2642b92c6726f1epng.png",
        }
    },
    methods: {
        // 初始化echarts
        echartsInit() {
            //柱形图
            //因为初始化echarts 的时候，需要指定的容器 id='main'
            this.$echarts.init(document.querySelector('#main')).setOption(
                {
                    // echarts选项，所有绘图数据和样式都在这里设置
                    title: {
                        text: `{b|${this.courseMsg.total}/${this.courseMsg.course_num}}`,
                        subtext: "{a|学生选课情况}",
                        subtextStyle: {
                            rich: {
                                a: {
                                    fontSize: "16",
                                },
                            },
                        },
                        textStyle: {
                            rich: {
                                b: {
                                    fontSize: "20",
                                    fontWeight: 'bold'
                                },
                            },
                        },
                        left: "center",
                        top: "center",
                    },
                    legend: {
                        bottom: '0',
                        left: 'center'
                    },
                    tooltip: {
                        //鼠标放到图上的数据展示样式
                        trigger: "item",
                    },
                    series: [
                        {
                            name: "课程成员情况",
                            type: "pie",
                            radius: ["50%", "70%"],
                            label: {
                                normal: {
                                    show: true,
                                    formatter: "{b}: \n{c}({d}%)", //自定义显示格式(b:name, c:value, d:百分比)
                                },
                            },
                            labelLine: {
                                show: true
                            },
                            data: [
                                // 扇形图数据格式： {value, name}
                                { value: this.courseMsg.total, name: '课程成员', itemStyle: { color: '#fc8251' } },
                                { value: this.courseMsg.course_num - this.courseMsg.total, name: '剩余空间', itemStyle: { color: '#cceabb' } },
                            ],
                        },
                    ],
                    toolbox: {
                        show: true,
                        feature: {
                            mark: { show: true },
                            dataView: {
                                show: true, readOnly: false
                            },
                            // restore: { show: true },
                            saveAsImage: { show: true },
                            myMore: {
                                show: true,
                                title: '课程成员',
                                icon: 'path://M432.45,595.444c0,2.177-4.661,6.82-11.305,6.82c-6.475,0-11.306-4.567-11.306-6.82s4.852-6.812,11.306-6.812C427.841,588.632,432.452,593.191,432.45,595.444L432.45,595.444z M421.155,589.876c-3.009,0-5.448,2.495-5.448,5.572s2.439,5.572,5.448,5.572c3.01,0,5.449-2.495,5.449-5.572C426.604,592.371,424.165,589.876,421.155,589.876L421.155,589.876z M421.146,591.891c-1.916,0-3.47,1.589-3.47,3.549c0,1.959,1.554,3.548,3.47,3.548s3.469-1.589,3.469-3.548C424.614,593.479,423.062,591.891,421.146,591.891L421.146,591.891zM421.146,591.891',
                                onclick: async (e) => {
                                    this.dialogUsers = true
                                    this.listLoading = true
                                    await this.getStudentBycourse()
                                    // 重新渲染，必须词步骤，否则无效果
                                    var echartsItem = this.$echarts.init(document.querySelector('#main'));
                                    echartsItem.setOption(e.getOption());
                                },
                            }
                        }
                    },
                })
        },
        // 获取该课程的成员信息
        async getStudentBycourse() {
            this.listLoading = true
            this.$message.info('获取信息')
            let res = await this.$axios.post('/mycourse/getstubycourse', { course_id: this.courseInfo.course_id, currentPage: this.currentPage })
            console.log(res);
            if (res.code == 200) {
                this.listLoading = false
                if (this.list) {
                    this.list = [...this.list, ...res.data].filter((user, index) => {
                        return index === [...this.list, ...res.data].findIndex(obj => {
                            return JSON.stringify(obj) === JSON.stringify(user);
                        });
                    });
                    this.total = res.total
                } else {
                    this.list = res.data
                    this.total = res.total
                }
            }
        },
        // 滚动到底部
        async handleScroll() {
            console.log((this.list ? this.list : []).length);
            if (this.total == (this.list ? this.list : []).length) {
                this.$message.info('已加载全部')
            }
            else {
                this.$message.info('滚动到底部')
                this.currentPage += 1
                await this.getStudentBycourse()
            }
        },
        // 邀请新成员
        async Invite() {
            this.$message.info('邀请新成员')
            this.drawer = true
            await this.getStuDrawList(this.class_id)
        },
        // 获取对应班级未选该门课程的学生列表
        async getStuDrawList(class_id) {
            this.drawLoading = true
            this.$message.info('添加学生')
            let res = await this.$axios.post('/mycourse/getstudrawlist', { class_id: class_id, course_id: this.courseInfo.course_id, grade_id: this.courseInfo.grade_id })
            console.log(res);
            if (res.code == 200) {
                this.drawLoading = false
                this.classOptions = res.cladata.map(item => {
                    return { label: item.class_name, value: item.class_id }
                })
                if (this.class_id == '') {
                    this.class_id = res.cladata[0].class_id
                }
                this.drawList = res.studata
            }
            else {
                this.$notify.info({
                    title: '消息',
                    message: res.msg
                });
                setTimeout(() => {
                    this.drawer = false
                }, 2000)
            }
        },
        // 选中班级
        async pitch(val) {
            if (val) {
                console.log(val)
                await this.getStuDrawList(val)
            }
        },
        toggleSelection(rows) {
            if (rows) {
                rows.forEach(row => {
                    this.$refs.multipleTable.toggleRowSelection(row);
                });
            } else {
                this.$refs.multipleTable.clearSelection();
            }
        },
        handleSelectionChange(val) {
            this.multipleSelection = val;
            console.log(val);
        },
        // 确认添加学生
        async InviteConfirm() {
            console.log(this.multipleSelection);
            if (this.multipleSelection.length == 0) {
                this.$notify({
                    title: '警告',
                    message: '请选择要添加的学生成员',
                    type: 'warning'
                });
            } else {
                let res = await this.$axios.post('/mycourse/inviteconfirm', {
                    list: this.multipleSelection.map(item => {
                        return { student_id: item.student_id, user_id: item.user_id }
                    }),
                    course_id: this.courseInfo.course_id,
                    course_name: this.courseMsg.course_name,
                    sender: this.userInfo.user_id
                })
                console.log(res);
                if (res.code == 200) {
                    this.$notify({
                        title: '成功',
                        message: '添加成功',
                        type: 'success'
                    });
                    this.drawer = false
                    await this.getStudentBycourse()
                    await this.getCourse()
                    this.echartsInit()
                } else {
                    this.$notify.error({
                        title: '错误',
                        message: '添加失败'
                    });
                }
            }
        },
        // 将标准时间转换为YYYY-MM-DD HH:MM:SS类型的
        formTime(time) {
            let newtime = new Date(time);
            // console.log(new Date(time), "要进行转换的时间");
            const year = newtime.getFullYear();
            const month = String(newtime.getMonth() + 1).padStart(2, "0");
            const day = String(newtime.getDate()).padStart(2, "0");
            // const hours = String(newtime.getHours()).padStart(2, "0");
            // const minutes = String(newtime.getMinutes()).padStart(2, "0");
            // const seconds = String(newtime.getSeconds()).padStart(2, "0");

            const formattedDate = `${year}-${month}-${day}`;
            return formattedDate;
        },
        // 将头像组件中的路由再传递给homeview
        async change(msg) {
            console.log(msg);
            if (msg == 'update') {
                await this.getCourse()
            }
            this.$emit("transfer", msg);
        },
        // 获取数据库数据
        async getCourse() {
            let res = await this.$axios.post('/mycourse/getdetail', this.courseInfo)
            console.log(res);
            if (res.code == 200) {
                this.courseMsg = { ...res.data[0], course_image: res.data[0].course_image ? `http://localhost:3000/image/getcourseimage/${encodeURIComponent(res.data[0].course_image)}` : res.data[0].course_image, avatar: res.data[0].avatar ? `http://localhost:3000/image/getavatar/${encodeURIComponent(res.data[0].avatar)}` : res.data[0].avatar, total: res.total, apply_start_date: this.formTime(res.data[0].apply_start_date), apply_end_date: this.formTime(res.data[0].apply_end_date), start_date: this.formTime(res.data[0].start_date), end_date: this.formTime(res.data[0].end_date) }
                console.log(this.courseMsg);
            }
        },
        // 去首页
        goHome() {
            if (this.userInfo.user_auth == 'teacher_per') {
                this.$router.push(
                    {
                        path: '/home/teachercourse',
                        // query: { id: keyPath[0] }
                    }
                )
                this.$emit("transfer", '/home/teachercourse');
            }
            if (this.userInfo.user_auth == 'student_per') {
                this.$router.push(
                    {
                        path: '/home/studentcourse',
                        // query: { id: keyPath[0] }
                    }
                )
                this.$emit("transfer", '/home/studentcourse');
            }
        },
        // 修改信息弹框
        showDia() {
            this.dialogFormVisible = true
            this.form.num = this.courseMsg.course_num
        },
        // 裁剪弹框
        show() {
            console.log(this.courseMsg.course_image);
            this.nowImage = this.courseMsg.course_image ? this.courseMsg.course_image : 'https://pic1.zhimg.com/80/v2-366c0aeae2b4050fa2fcbfc09c74aad4_720w.jpg'

            console.log(this.nowImage);
            this.dialogCropper = true
        },
        // 裁剪图片后返回的blob
        async handleBlobData(blob) {
            // 处理 Blob 对象
            console.log(blob);
            const reader = new FileReader();
            reader.onload = () => {
                this.fileContent = reader.result;
            };
            reader.readAsDataURL(blob);
            let fd = new FormData()
            fd.append('course_image', blob)
            this.fileData = fd;
            console.log(this.fileData);
        },
        // 上传图片
        async uploadImg() {
            let res = await this.$axios.post(`/mycourse/uploadimg/${this.courseInfo.course_id}`, this.fileData)
            console.log(res);
            if (res.code == 200) {
                await this.getCourse()
                this.$message.success('上传成功!')
                this.loading = false
            }
        },
        // 修改课程总人数
        async Sub() {
            this.dialogFormVisible = false
            let res = await this.$axios.post(`/mycourse/changenum`, { course_id: this.courseInfo.course_id, course_num: this.form.num })
            console.log(res);
            if (res.code == 200) {
                await this.getCourse()
                this.echartsInit()
                this.$message.success(res.msg)
            }
        },
    },
    async mounted() {
        console.log(JSON.parse(JSON.stringify(this.$store.state.user_info)));
        this.userInfo = {
            ...JSON.parse(JSON.stringify(this.$store.state.user_info))
        };
        console.log(this.$route.query);
        this.courseInfo = this.$route.query
        console.log(this.courseInfo);
        await this.getCourse()
        this.echartsInit()
    },
}
</script>
  
  <!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.container {
    width: 98%;
    height: 98%;
    margin: 3px auto;
    opacity: 1;
    border-radius: 17px;
    background: rgba(255, 255, 255, 1);
    box-shadow: 0px 0px 0px 0px rgba(168, 159, 159, 0.1), -23px 19px 65px 0px rgba(168, 159, 159, 0.1), -92px 74px 118px 0px rgba(168, 159, 159, 0.09), -208px 167px 160px 0px rgba(168, 159, 159, 0.05), -370px 297px 190px 0px rgba(168, 159, 159, 0.01), -578px 463px 207px 0px rgba(168, 159, 159, 0);
}

.header {
    width: 100%;
    height: 80px;
    border-bottom: 2px solid #bbb;
    background-color: #fff;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.courses {
    width: 90%;
    height: 90%;
    /* border: 1px solid #000; */
    margin: 10px auto;

}

.content {
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    align-items: center;
}

.imgbox {
    width: 500px;
    height: 230px;
    background-color: #ccc;
    font-size: 30px;
    overflow: hidden;
    border-radius: 10px;
    display: flex;
    justify-content: center;
    align-items: center;
}

.img {
    height: 320px;
}

.hometxt {
    border-bottom: 3px solid #cceabb;
    padding-bottom: 10px;
    font-weight: 600;
    cursor: pointer;
}

.Tavatar {
    width: 50px;
    height: 50px;
    border-radius: 5px;
}
</style>